package com.chixing.commons;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/webSocket/{id}")
public class WebSocketProcess {
    //websocket对象以key-value存储到线程安全的集合中
    private static ConcurrentHashMap<Long,WebSocketProcess> concurrentHashMap = new ConcurrentHashMap<>(12);
    //会话对象
    private Session session;
    //客户端连接时出发
    @OnOpen
    public void onOpen(Session session, @PathParam("id") long id){
        //System.out.println(id);
        //每建立一个新的连接,就把当前客户的id为key，this为value存到集合中
        this.session = session;
        concurrentHashMap.put(id,this);
        log.info("Open a websocket. id={}", id);
    }
    //客户端关闭连接时触发
    @OnClose
    public void onClose(Session session, @PathParam("id") long id) {
        //客户端连接关闭时，移除map中存储的键值对
        concurrentHashMap.remove(id);
        log.info("close a websocket, concurrentHashMap remove sessionId= {}", id);
    }
    //用户接收到消息时触发
    @OnMessage
    public void onMessage(String message, @PathParam("id") String id) {
        log.info("receive a message from client id={},msg={}", id, message);
    }
    //连接发生异常时触发
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Error while websocket. ", error);
    }
    //消息发送到指定的客户端
    public void sendMessage(long id, String message)throws Exception{
        //根据id获取连接对象
        WebSocketProcess webSocketProcess = concurrentHashMap.get(id);
        System.out.println(webSocketProcess);
        if(!ObjectUtils.isEmpty(webSocketProcess)){
            if(webSocketProcess.session.isOpen()){
                webSocketProcess.session.getBasicRemote().sendText(message);
            }else {
                log.error("websocket session={} is closed ", id);
            }
        }else {
            log.error("websocket session={} is not exit ", id);
        }
    }

    //消息发送到所有的客户端
    public void sendAllMessage(String message)throws Exception{
        //在线客户端数量
        log.info("online client count={}", concurrentHashMap.size());
        //获取客户端id的集合
        Set<Map.Entry<Long, WebSocketProcess>> entries = concurrentHashMap.entrySet();
        for (Map.Entry<Long, WebSocketProcess> entry : entries) {
            Long cid = entry.getKey();
            WebSocketProcess webSocketProcess = entry.getValue();
            boolean sessionOpen = webSocketProcess.session.isOpen();
            if (sessionOpen) {
                webSocketProcess.session.getBasicRemote().sendText(message);// 服务器向该客户端 发送消息
            } else {
                log.info("cid={} is closed,ignore send text", cid);
            }
        }
    }
}
